package ru.spb.osll.myfit.client;

import ru.spb.osll.myfit.client.dialog.ErrorDialog;
import ru.spb.osll.myfit.client.service.FitService;
import ru.spb.osll.myfit.client.service.FitServiceAsync;
import ru.spb.osll.myfit.client.view.IView;
import ru.spb.osll.myfit.client.view.ViewLoader;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Fitnesse implements EntryPoint {

  private ErrorDialog m_errorDialog = new ErrorDialog();

  /**
   * Create a remote service proxy to talk to the server-side Fit service.
   */
  private final FitServiceAsync m_fitService = GWT.create(FitService.class);

  private final ViewLoader m_viewLoader = new ViewLoader();

  public void onModuleLoad() {
    createView();
  }

  /**
   * Get screen width
   * 
   * @return screen width
   */
  native public static int getScreenWidth()/*-{
                                           return $wnd.screen.width;
                                           }-*/;

  /**
   * Set page path from address bar.
   */
  private void createView() {
    m_fitService.getPagePath(new AsyncCallback<String>() {

      @Override
      public void onFailure(Throwable caught) {
        caught.printStackTrace();
        m_errorDialog.setMessage(caught);
        m_errorDialog.center();
      }

      @Override
      public void onSuccess(String result) {
        IView view = m_viewLoader.getView(result);
        setRootWidget(view.getRootWidget());
      }
    });
  }

  private void setRootWidget(Widget rootWidget) {
    RootPanel.get().add(rootWidget);
  }
}